<template>
    <div class="borrow-manage">
        <div class="toolbar">
            <el-input v-model="search" placeholder="搜索读者/书名/ISBN" style="width:240px;margin-right:12px;" clearable
                @keyup.enter="onSearch" />
            <el-button type="success" class="search-btn" @click="onSearch" style="margin-right:12px;">搜索</el-button>
            <el-button type="primary" @click="onAdd">新增借阅</el-button>
        </div>
        <el-table :data="pagedRecords" style="width:100%;margin-top:16px;" border stripe :loading="tableLoading"
            :header-cell-style="{ textAlign: 'center', background: '#f5f7fa', fontWeight: 'bold' }"
            :cell-style="{ textAlign: 'center' }">
            <el-table-column prop="user.name" label="读者姓名" min-width="100" fixed="left" />
            <el-table-column prop="user.username" label="账号" min-width="100" />
            <el-table-column prop="book.title" label="书名" min-width="120" />
            <el-table-column prop="book.isbn" label="ISBN" min-width="120" />
            <el-table-column prop="borrowDate" label="借出日期" min-width="110">
                <template #default="scope">{{ formatDate(scope.row.borrowDate) }}</template>
            </el-table-column>
            <el-table-column prop="dueDate" label="应还日期" min-width="110">
                <template #default="scope">{{ formatDate(scope.row.dueDate) }}</template>
            </el-table-column>
            <el-table-column prop="returnDate" label="归还日期" min-width="110">
                <template #default="scope">{{ formatDate(scope.row.returnDate) }}</template>
            </el-table-column>
            <el-table-column prop="renewCount" label="续借次数" min-width="80" />
            <el-table-column prop="fine" label="罚金" min-width="80" />
            <el-table-column label="操作" min-width="160" fixed="right">
                <template v-slot="scope">
                    <el-button size="small" @click="onEdit(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="onDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div style="margin:16px 0;display:flex;align-items:center;">
            <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
                :total="total" layout="total, sizes, prev, pager, next, jumper" style="margin-left:auto;"
                @current-change="onPageChange" @size-change="onPageSizeChange" />
        </div>
        <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑借阅' : '新增借阅'" width="420px">
            <el-form :model="editForm" label-width="90px">
                <el-form-item label="读者" required>
                    <el-select v-model="editForm.userId" filterable placeholder="请选择读者">
                        <el-option v-for="u in users" :key="u.id" :label="u.name" :value="u.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="图书" required>
                    <el-select v-model="editForm.bookId" filterable placeholder="请选择图书">
                        <el-option v-for="b in availableBooks" :key="b.id" :label="b.title" :value="b.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="借出日期" required>
                    <el-date-picker v-model="editForm.borrowDate" type="date" value-format="YYYY-MM-DD"
                        :disabled="!isEdit" />
                </el-form-item>
                <el-form-item label="应还日期" required>
                    <el-date-picker v-model="editForm.dueDate" type="date" value-format="YYYY-MM-DD"
                        :disabled-date="disabledDueDate" />
                </el-form-item>
                <el-form-item label="归还日期">
                    <el-date-picker v-model="editForm.returnDate" type="date" value-format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item label="续借次数">
                    <el-input-number v-model="editForm.renewCount" :min="0" :max="2" />
                </el-form-item>
                <el-form-item label="罚金">
                    <el-input-number v-model="editForm.fine" :min="0" :step="0.1" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="onSave">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

const records = ref([])
const users = ref([])
const books = ref([])
const search = ref('')
const dialogVisible = ref(false)
const editForm = ref({
    id: undefined,
    userId: null,
    bookId: null,
    borrowDate: '',
    dueDate: '',
    returnDate: '',
    renewCount: 0,
    fine: 0
})
const isEdit = ref(false)
const tableLoading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const pagedRecords = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value
    return records.value.slice(start, start + pageSize.value)
})

const availableBooks = computed(() => {
    if (!books.value || books.value.length === 0) return []
    if (!isEdit.value || !editForm.value.bookId) {
        return books.value.filter(b => b.status === '在馆')
    }
    return books.value.filter(b => b.status === '在馆' || b.id === editForm.value.bookId)
})

const fetchRecords = async (keyword = '') => {
    tableLoading.value = true
    let url = '/borrows'
    try {
        const res = await axios.get(url)
        if (Array.isArray(res.data)) {
            if (keyword) {
                records.value = res.data.filter(r =>
                    r.user?.name?.includes(keyword) ||
                    r.user?.username?.includes(keyword) ||
                    r.book?.title?.includes(keyword) ||
                    r.book?.isbn?.includes(keyword)
                )
            } else {
                records.value = res.data
            }
            total.value = records.value.length
        } else {
            records.value = res.data.list || []
            total.value = res.data.total || records.value.length
        }
    } catch (e) {
        records.value = []
        total.value = 0
        ElMessage.error('获取借阅记录失败')
    }
    tableLoading.value = false
    currentPage.value = 1
}
const fetchUsers = async () => {
    const res = await axios.get('/readers')
    // 只保留状态为“正常”的读者
    users.value = res.data.filter(u => u.status === '正常').map(u => ({ ...u, id: Number(u.id) }))
}
const fetchBooks = async () => {
    const res = await axios.get('/books')
    books.value = res.data
}
onMounted(() => {
    fetchRecords()
    fetchUsers()
    fetchBooks()
})
const onSearch = () => {
    fetchRecords(search.value)
}
const resetEditForm = () => {
    editForm.value = {
        id: undefined,
        userId: null,
        bookId: null,
        borrowDate: '',
        dueDate: '',
        returnDate: '',
        renewCount: 0,
        fine: 0
    }
}

const onAdd = () => {
    if (users.value.length === 0 || books.value.length === 0) {
        ElMessage.warning('请稍候，读者和图书数据正在加载...')
        return
    }
    const today = new Date()
    editForm.value = {
        id: undefined,
        userId: null,
        bookId: null,
        borrowDate: formatDate(today),
        dueDate: formatDate(new Date(today.getTime() + 14 * 24 * 60 * 60 * 1000)),
        returnDate: '',
        renewCount: 0,
        fine: 0
    }
    isEdit.value = false
    dialogVisible.value = true
}

const onEdit = async (row) => {
    if (!users.value.length) await fetchUsers()
    if (!books.value.length) await fetchBooks()
    let userId = row.user?.id ?? row.user
    let bookId = row.book?.id ?? row.book
    userId = Number(userId)
    bookId = Number(bookId)
    editForm.value = {
        id: row.id,
        userId,
        bookId,
        borrowDate: row.borrowDate,
        dueDate: row.dueDate,
        returnDate: row.returnDate,
        renewCount: row.renewCount,
        fine: row.fine
    }
    isEdit.value = true
    dialogVisible.value = true
}
watch(dialogVisible, v => { if (!v) resetEditForm() })

const onPageChange = (page) => {
    currentPage.value = page
}
const onPageSizeChange = (size) => {
    pageSize.value = size
    currentPage.value = 1
}
const onSave = async () => {
    if (!editForm.value.userId || !editForm.value.bookId || !editForm.value.borrowDate || !editForm.value.dueDate) {
        ElMessage.error('请填写完整信息')
        return
    }
    const userObj = users.value.find(u => u.id === editForm.value.userId)
    const bookObj = books.value.find(b => b.id === editForm.value.bookId)
    if (!userObj || !bookObj) {
        ElMessage.error('请选择有效的读者和图书')
        return
    }
    if (!editForm.value.id) {
        const book = books.value.find(b => b.id === editForm.value.bookId)
        if (!book || book.status !== '在馆') {
            ElMessage.error('该图书已被借出或不可借')
            return
        }
    }
    const borrowDate = new Date(editForm.value.borrowDate)
    const dueDate = new Date(editForm.value.dueDate)
    if (dueDate < borrowDate) {
        ElMessage.error('应还日期不能早于借出日期')
        return
    }
    if ((dueDate - borrowDate) / (1000 * 60 * 60 * 24) > 14) {
        ElMessage.error('应还日期最多只能比借出日期晚15天')
        return
    }
    try {
        const payload = {
            user: { id: userObj.id },
            book: { id: bookObj.id },
            borrowDate: editForm.value.borrowDate,
            dueDate: editForm.value.dueDate,
            returnDate: editForm.value.returnDate,
            renewCount: editForm.value.renewCount,
            fine: editForm.value.fine
        }
        if (editForm.value.id) {
            await axios.put(`/borrows/${editForm.value.id}`, payload)
            ElMessage.success('编辑成功')
        } else {
            await axios.post('/borrows', payload)
            ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        await fetchRecords(search.value)
        await fetchBooks()
    } catch (e) {
        ElMessage.error('保存失败')
    }
}
const onDelete = async (row) => {
    try {
        await ElMessageBox.confirm('确定要删除该借阅记录吗？', '删除', { type: 'warning' })
        await axios.delete(`/borrows/${row.id}`)
        ElMessage.success('删除成功')
        fetchRecords(search.value)
        await fetchBooks()
    } catch (e) {
        ElMessage.error('删除失败')
    }
}
function formatDate(date) {
    if (!date) return ''
    if (typeof date === 'string') return date.length > 10 ? date.slice(0, 10) : date
    const y = date.getFullYear()
    const m = String(date.getMonth() + 1).padStart(2, '0')
    const d = String(date.getDate()).padStart(2, '0')
    return `${y}-${m}-${d}`
}
function disabledDueDate(date) {
    const borrow = editForm.value.borrowDate ? new Date(editForm.value.borrowDate) : new Date()
    const min = new Date(borrow.getFullYear(), borrow.getMonth(), borrow.getDate())
    const max = new Date(min.getTime() + 14 * 24 * 60 * 60 * 1000)
    return date < min || date > max
}
</script>

<style scoped>
.borrow-manage {
    padding: 24px;
}

.toolbar {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
}
</style>
